package com.sdy.dcsb.provider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.api.DcsbApi;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.model.EsbSystemService;
import com.sdy.dcsb.biz.service.*;
import com.sdy.mvc.annotation.RemoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 *  RPC调用
 * </p>
 */
@Slf4j
@RemoteService
public class DcsbProvider implements DcsbApi {
    @Autowired
    private EsbInboundMainService esbInboundMainService;
    @Autowired
    private EsbConsumerSystemIpService esbConsumerSystemIpService;
    @Autowired
    private EsbConsumerSystemIpGroupService esbConsumerSystemIpGroupService;
    @Autowired
    private EsbConsumerTreeService esbConsumerTreeService;
    @Autowired
    private EsbSystemServiceService esbSystemServiceService;
    @Autowired
    private EsbServiceConsumerService esbServiceConsumerService;
    @Autowired
    private EsbAtomServiceService esbAtomServiceService;
    @Autowired
    private EsbAdapderHttpService esbAdapderHttpService;
    @Autowired
    private EsbAdapderSoapService esbAdapderSoapService;
    @Autowired
    private EsbAppService esbAppService;
    @Autowired
    private EsbServiceAtomDeployService esbServiceAtomDeployService;
    @Autowired
    private EsbServiceTreeService esbServiceTreeService;
    @Autowired
    private EsbInboundHttpService esbInboundHttpService;
    @Autowired
    private EsbInboundWebserviceService esbInboundWebserviceService;
    @Autowired
    private EsbInboundH5Service esbInboundH5Service;
    @Autowired
    private EsbServiceApiService esbServiceApiService;
    @Autowired
    private EsbServiceApiLogService esbServiceApiLogService;

    @Override
    public Response openInterfaceServiceAuthority(List<String> addressList, String deptNamePath, String groupName, String[] ip) {
        if(!isEmpty(addressList) && addressList.size() != 0 && !isEmpty(deptNamePath) && !isEmpty(groupName) && !isEmpty(ip) && ip.length != 0) {
            for(int h=0; h<addressList.size(); h++) {
                String address = addressList.get(h);
                if(address.contains("/DCSBWeb/")) {
                    String code = "";
                    String version = "";
                    if(address.contains("/DCSBWeb/h5servlets")) {
                        address = address.substring(address.indexOf("/DCSBWeb/")+20);
                    }else {
                        address = address.substring(address.indexOf("/DCSBWeb/")+18);
                    }
                    if(address.contains("@")) {
                        code = address.substring(0, address.indexOf("@"));
                        version = address.substring(address.indexOf("@")+1);
                        // 通过服务编码和版本查询服务是否存在
                        QueryWrapper<EsbInboundMain> esbInboundMainWrapper = new QueryWrapper<>();
                        esbInboundMainWrapper.eq("servcode", code);
                        esbInboundMainWrapper.eq("servversion", version);
                        List<EsbInboundMain> esbInboundMainWrapperResult = esbInboundMainService.list(esbInboundMainWrapper);
                        if(esbInboundMainWrapperResult.size() == 0) {
                            return Response.error("提供的接口路径有误，服务不存在");
                        }
                        Integer serviceid = esbInboundMainWrapperResult.get(0).getServiceid();

                        // 处理ip的归属群组位置
                        List<String> ipExistence = new ArrayList<String>();
                        List<String> ipNnexistence = new ArrayList<String>();
                        List<Integer> ipExistenceGroup = new ArrayList<Integer>();
                        List<Integer> ipExistenceSystem = new ArrayList<Integer>();
                        for(int i=0; i<ip.length; i++){
                            QueryWrapper<EsbConsumerSystemIp> esbConsumerSystemIpWrapper = new QueryWrapper<>();
                            esbConsumerSystemIpWrapper.eq("ip", ip[i]);
                            List<EsbConsumerSystemIp> esbConsumerSystemIpWrapperResult = esbConsumerSystemIpService.list(esbConsumerSystemIpWrapper);
                            if(esbConsumerSystemIpWrapperResult.size() == 0) {
                                ipNnexistence.add(ipNnexistence.size(), ip[i]);
                            }else {
                                ipExistence.add(ipExistence.size(), ip[i]);
                                if(ipExistenceGroup.size() == 0) {
                                    ipExistenceGroup.add(ipExistenceGroup.size(), esbConsumerSystemIpWrapperResult.get(0).getGroupid());
                                }else {
                                    Integer count = 0;
                                    for(int j=0; j<ipExistenceGroup.size(); j++) {
                                        if(esbConsumerSystemIpWrapperResult.get(0).getGroupid().equals(ipExistenceGroup.get(j))) {
                                            count++;
                                        }
                                    }
                                    if(count == 0) {
                                        ipExistenceGroup.add(ipExistenceGroup.size(), esbConsumerSystemIpWrapperResult.get(0).getGroupid());
                                    }
                                }
                                if(ipExistenceSystem.size() == 0){
                                    ipExistenceSystem.add(ipExistenceSystem.size(), esbConsumerSystemIpWrapperResult.get(0).getSystemid());
                                }else {
                                    Integer count = 0;
                                    for(int j=0; j<ipExistenceSystem.size(); j++) {
                                        if(esbConsumerSystemIpWrapperResult.get(0).getSystemid().equals(ipExistenceSystem.get(j))) {
                                            count++;
                                        }
                                    }
                                    if(count == 0) {
                                        ipExistenceSystem.add(ipExistenceSystem.size(), esbConsumerSystemIpWrapperResult.get(0).getSystemid());
                                    }
                                }
                            }
                        }
                        // 存放消费者的系统id
                        Integer consumerSystemId = 0;
                        if(ipExistence.size() == 0) {
                            QueryWrapper<EsbConsumerSystemIpGroup> esbConsumerSystemIpGroupWrapper = new QueryWrapper<>();
                            esbConsumerSystemIpGroupWrapper.eq("groupname", groupName);
                            List<EsbConsumerSystemIpGroup> esbConsumerSystemIpGroupResult = esbConsumerSystemIpGroupService.list(esbConsumerSystemIpGroupWrapper);
                            if(esbConsumerSystemIpGroupResult.size() == 0){
                                if(deptNamePath.contains("/")) {
                                    if("/".equals(deptNamePath.substring(0, 1))) {
                                        return Response.error("部门全路径名称有误，不要以/开头");
                                    }
                                    String[] deptName = deptNamePath.split("/");
                                    Integer systemId = esbConsumerTreeService.createSystemGroup(0, 1,1, deptName, 1);
                                    consumerSystemId = systemId;
                                    // 处理新增自建系统
                                    EsbConsumerSystemIpGroup esbConsumerSystemIpGroup = new EsbConsumerSystemIpGroup();
                                    esbConsumerSystemIpGroup.setSystemid(systemId);
                                    esbConsumerSystemIpGroup.setGroupname(groupName);
                                    esbConsumerSystemIpGroup.setGroupcode("");
                                    esbConsumerSystemIpGroup.setAppowner("");
                                    esbConsumerSystemIpGroupService.save(esbConsumerSystemIpGroup);
                                    // 自建系统下新增ip
                                    for(int i=0; i<ipNnexistence.size(); i++) {
                                        EsbConsumerSystemIp esbConsumerSystemIp = new EsbConsumerSystemIp();
                                        esbConsumerSystemIp.setSystemid(systemId);
                                        esbConsumerSystemIp.setGroupid(esbConsumerSystemIpGroup.getGroupid());
                                        esbConsumerSystemIp.setIp(ipNnexistence.get(i));
                                        esbConsumerSystemIp.setPort("0");
                                        esbConsumerSystemIp.setStatus("1");
                                        esbConsumerSystemIpService.save(esbConsumerSystemIp);
                                        consumer(esbConsumerSystemIp.getId(), systemId);
                                    }

                                }else {
                                    return Response.error("部门全路径名称有误");
                                }
                            }else {
                                for(int i=0; i<ipNnexistence.size(); i++) {
                                    consumerSystemId = esbConsumerSystemIpGroupResult.get(0).getSystemid();
                                    EsbConsumerSystemIp esbConsumerSystemIp = new EsbConsumerSystemIp();
                                    esbConsumerSystemIp.setSystemid(consumerSystemId);
                                    esbConsumerSystemIp.setGroupid(esbConsumerSystemIpGroupResult.get(0).getGroupid());
                                    esbConsumerSystemIp.setIp(ipNnexistence.get(i));
                                    esbConsumerSystemIp.setPort("0");
                                    esbConsumerSystemIp.setStatus("1");
                                    esbConsumerSystemIpService.save(esbConsumerSystemIp);
                                    consumer(esbConsumerSystemIp.getId(), consumerSystemId);
                                }
                            }
                        }else {
                            if(ipExistenceGroup.size() == 1) {
                                consumerSystemId = ipExistenceSystem.get(0);
                                for(int i=0; i<ipNnexistence.size(); i++) {
                                    EsbConsumerSystemIp esbConsumerSystemIp = new EsbConsumerSystemIp();
                                    esbConsumerSystemIp.setSystemid(consumerSystemId);
                                    esbConsumerSystemIp.setGroupid(ipExistenceGroup.get(0));
                                    esbConsumerSystemIp.setIp(ipNnexistence.get(i));
                                    esbConsumerSystemIp.setPort("0");
                                    esbConsumerSystemIp.setStatus("1");
                                    esbConsumerSystemIpService.save(esbConsumerSystemIp);
                                    consumer(esbConsumerSystemIp.getId(), consumerSystemId);
                                }
                            }else {
                                Integer noPermissionCount = 0;
                                // 判断ip群组里的所有ip是否已经拥有接口的访问权限，一般用于人工操作DCSB赋权之后，能让共享平台完成实施工单
                                for(int i=0; i<ip.length; i++){
                                    QueryWrapper<EsbServiceConsumer> esbServiceConsumerQueryWrapper = new QueryWrapper<>();
                                    esbServiceConsumerQueryWrapper.eq("servcode", code);
                                    Integer ipid = 0;
                                    try{
                                        ipid = selectIpid(ip[i]);
                                    }catch (Exception e) {
                                        noPermissionCount++;
                                        break;
                                    }
                                    esbServiceConsumerQueryWrapper.eq("ipid", ipid);
                                    esbServiceConsumerQueryWrapper.eq("status", "0");
                                    List<EsbServiceConsumer> esbServiceConsumerResult = esbServiceConsumerService.list(esbServiceConsumerQueryWrapper);
                                    if(esbServiceConsumerResult.size() != 0) {
                                        noPermissionCount++;
                                        break;
                                    }
                                }
                                if(noPermissionCount == 0) {
                                    return Response.success("人工授权完成，实施成功");
                                }
                                return Response.error("此实施工单中自建系统的ip组存在于DCSB中不同的系统群组，请联系DCSB实施人员人工操作此实施单");
                            }
                        }

                        // 处理接口服务的消费信息
                        systemServiceInsert(serviceid, code, consumerSystemId);

                        // 开权限
                        for(int i=0; i<ip.length; i++){
                            EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
                            esbServiceConsumer.setStatus("1");
                            esbServiceConsumer.setUpdateTime(new Date());
                            esbServiceConsumerService.update(esbServiceConsumer, new UpdateWrapper<EsbServiceConsumer>().
                                    eq("servcode", code).eq("ipid", selectIpid(ip[i])));
                        }
                    }else {
                        return Response.error("提供的接口路径有误");
                    }
                }else {
                    return Response.error("提供的接口路径有误");
                }
            }
            return Response.success("授权完成，实施成功");
        }else {
            return Response.error("提供的请求数据不能为空");
        }
    }

    @Override
    public Response cancelInterfaceServiceAuthority(List<String> addressList, String[] ip) {
        if(!isEmpty(addressList) && addressList.size() !=0 && !isEmpty(ip) && ip.length != 0) {
            for(int h=0; h<addressList.size(); h++) {
                String address = addressList.get(h);
                if(!address.contains("/DCSBWeb/")) {
                    return Response.error("提供的接口路径有误");
                }
                String code = "";
                String version = "";
                if(address.contains("/DCSBWeb/h5servlets")) {
                    address = address.substring(address.indexOf("/DCSBWeb/") + 20);
                }else {
                    address = address.substring(address.indexOf("/DCSBWeb/") + 18);
                }
                if(!address.contains("@")) {
                    return Response.error("提供的接口路径有误");
                }
                code = address.substring(0, address.indexOf("@"));
                version = address.substring(address.indexOf("@") + 1);
                // 通过服务编码和版本查询服务是否存在
                QueryWrapper<EsbInboundMain> esbInboundMainWrapper = new QueryWrapper<>();
                esbInboundMainWrapper.eq("servcode", code);
                esbInboundMainWrapper.eq("servversion", version);
                List<EsbInboundMain> esbInboundMainWrapperResult = esbInboundMainService.list(esbInboundMainWrapper);
                if(esbInboundMainWrapperResult.size() == 0) {
                    return Response.error("提供的接口路径有误，服务不存在");
                }
                List<Integer> ipid = new ArrayList<Integer>();
                for(int i=0; i<ip.length; i++) {
                    QueryWrapper<EsbConsumerSystemIp> esbConsumerSystemIpWrapper = new QueryWrapper<>();
                    esbConsumerSystemIpWrapper.eq("ip", ip[i]);
                    List<EsbConsumerSystemIp> esbConsumerSystemIpWrapperResult = esbConsumerSystemIpService.list(esbConsumerSystemIpWrapper);
                    if(esbConsumerSystemIpWrapperResult.size() != 0) {
                        ipid.add(ipid.size(), esbConsumerSystemIpWrapperResult.get(0).getId());
                    }
                }
                for(int i=0; i<ipid.size(); i++) {
                    QueryWrapper<EsbServiceConsumer> esbServiceConsumerQueryWrapper = new QueryWrapper<>();
                    esbServiceConsumerQueryWrapper.eq("servcode", code);
                    esbServiceConsumerQueryWrapper.eq("ipid", ipid.get(i));
                    esbServiceConsumerQueryWrapper.eq("status", "1");
                    List<EsbServiceConsumer> esbServiceConsumerResult = esbServiceConsumerService.list(esbServiceConsumerQueryWrapper);
                    // 取消权限
                    if(esbServiceConsumerResult.size() != 0) {
                        EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
                        esbServiceConsumer.setStatus("0");
                        esbServiceConsumer.setUpdateTime(new Date());
                        esbServiceConsumerService.update(esbServiceConsumer, new UpdateWrapper<EsbServiceConsumer>().
                                eq("servcode", code).eq("ipid", ipid.get(i)));
                    }
                }
            }
            return Response.success("取消权限完成，实施成功");
        }else {
            return Response.error("提供的请求数据不能为空");
        }
    }
    /**
     * ip新增时判断ip所在系统是否存在于服务的消费信息内，若存在则需要在权限控制表新增记录
     * @param ipid, ip对应的id
     * @param systemId
     */
    private void consumer(Integer ipid, Integer systemId) {
        QueryWrapper<EsbSystemService> esbSystemServiceWrapper = new QueryWrapper<>();
        esbSystemServiceWrapper.eq("system_id", systemId);
        List<EsbSystemService> esbSystemServiceWrapperResult = esbSystemServiceService.list(esbSystemServiceWrapper);
        for(int i=0; i<esbSystemServiceWrapperResult.size(); i++) {
            EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
            esbServiceConsumer.setServcode(esbSystemServiceWrapperResult.get(i).getServcode());
            esbServiceConsumer.setIpid(ipid);
            esbServiceConsumer.setStatus("0");
            esbServiceConsumer.setCreateTime(new Date());
            esbServiceConsumer.setUpdateTime(new Date());
            esbServiceConsumerService.save(esbServiceConsumer);
        }
    }

    /**
     * 服务的消费信息控制自增
     * @param serviceid
     * @param servcode
     * @param systemId
     */
    private void systemServiceInsert(Integer serviceid, String servcode, Integer systemId) {
        QueryWrapper<EsbSystemService> esbSystemServiceWrapper = new QueryWrapper<>();
        esbSystemServiceWrapper.eq("serviceid",serviceid);
        esbSystemServiceWrapper.eq("servcode", servcode);
        esbSystemServiceWrapper.eq("system_id", systemId);
        List<EsbSystemService> esbSystemServiceWrapperResult = esbSystemServiceService.list(esbSystemServiceWrapper);
        if(esbSystemServiceWrapperResult.size() == 0) {
            EsbSystemService esbSystemService = new EsbSystemService();
            esbSystemService.setServiceid(serviceid);
            esbSystemService.setServcode(servcode);
            esbSystemService.setSystemId(systemId);
            esbSystemService.setMaxclient(20);
            esbSystemService.setUnit1("86400");
            esbSystemService.setReqFrequency("2000");
            if(esbSystemServiceService.save(esbSystemService)) {
                QueryWrapper<EsbConsumerSystemIp> wrapper = new QueryWrapper<>();
                wrapper.eq("systemid", systemId);
                List<EsbConsumerSystemIp> result = esbConsumerSystemIpService.list(wrapper);
                for(int i=0; i<result.size(); i++) {
                    Integer ipid = result.get(i).getId();
                    EsbServiceConsumer esbServiceConsumer = new EsbServiceConsumer();
                    esbServiceConsumer.setServcode(servcode);
                    esbServiceConsumer.setIpid(ipid);
                    esbServiceConsumer.setStatus("0");
                    esbServiceConsumer.setCreateTime(new Date());
                    esbServiceConsumer.setUpdateTime(new Date());
                    esbServiceConsumerService.save(esbServiceConsumer);
                }
            }
        }
    }

    /**
     * 查询ip对应的id
     * @param ip
     * @return
     */
    private Integer selectIpid(String ip) {
        QueryWrapper<EsbConsumerSystemIp> esbConsumerSystemIpQueryWrapper = new QueryWrapper<>();
        esbConsumerSystemIpQueryWrapper.eq("ip", ip);
        List<EsbConsumerSystemIp> esbConsumerSystemIpResult = esbConsumerSystemIpService.list(esbConsumerSystemIpQueryWrapper);
        return esbConsumerSystemIpResult.get(0).getId();
    }

    @Override
    public Response registeredInterfaceAuthority(String interfaceName, Integer adapterType, Integer contentType, String url,
                                                 Integer httpType) {
        if(isEmpty(interfaceName) || isEmpty(adapterType) || isEmpty(contentType) || isEmpty(url) || isEmpty(httpType)) {
            return Response.error("提供的请求数据不能为空");
        }
        // 原子服务注册
        EsbAtomservice esbAtomservice = new EsbAtomservice();
        // 提供者系统id
        esbAtomservice.setSystemId(397);
        esbAtomservice.setAtomserviceName(interfaceName);
        esbAtomservice.setAtomserviceCode(atomCodeAutoincrement());
        esbAtomservice.setAdapterType(adapterType.toString());
        esbAtomservice.setContentType(contentType.toString());
        esbAtomservice.setMaxClients("1000");
        esbAtomservice.setAtomserviceVersion("1.0");
        esbAtomservice.setStatus("1");
        esbAtomservice.setOverTime("30000");
        esbAtomservice.setCreateTime(new Date());
        try{
            esbAtomServiceService.save(esbAtomservice);
        }catch (Exception e) {
            return Response.error("注册失败，原子服务保存出错");
        }
        // 原子服务适配类型信息注册
        if(adapterType == 1) {
            EsbAdapderHttp esbAdapderHttp = new EsbAdapderHttp();
            esbAdapderHttp.setId(esbAtomservice.getId());
            esbAdapderHttp.setServiceUrl(url);
            esbAdapderHttp.setScharset("UTF-8");
            esbAdapderHttp.setRcharset("UTF-8");
            esbAdapderHttp.setHttptype(httpType.toString());
            try{
                esbAdapderHttpService.save(esbAdapderHttp);
            }catch (Exception e) {
                return Response.error("注册失败，原子适配类型保存出错");
            }
        }else if(adapterType == 2) {
            EsbAdapderSoap esbAdapderSoap = new EsbAdapderSoap();
            esbAdapderSoap.setId(esbAtomservice.getId());
            esbAdapderSoap.setServiceUrl(url);
            esbAdapderSoap.setScharset("UTF-8");
            esbAdapderSoap.setRcharset("UTF-8");
            try{
                esbAdapderSoapService.save(esbAdapderSoap);
            }catch (Exception e) {
                return Response.error("注册失败，原子适配类型保存出错");
            }
        }else {
            return Response.error("暂不支持此类型的注册");
        }
        // 原子服务部署信息注册
        deploy(1, esbAtomservice.getId());
        // 服务注册
        EsbInboundMain esbInboundMain = new EsbInboundMain();
        esbInboundMain.setServname(interfaceName);
        esbInboundMain.setServcode(serviceCodeAutoincrement());
        esbInboundMain.setServversion("1.0");
        esbInboundMain.setStatus("1");
        esbInboundMain.setAtomcode(esbAtomservice.getAtomserviceCode());
        esbInboundMain.setOverTime("30000");
        esbInboundMain.setCreateTime(new Date());
        try{
            esbInboundMainService.save(esbInboundMain);
        }catch (Exception e) {
            return Response.error("注册失败，服务保存出错");
        }
        EsbServiceTree esbServiceTree = new EsbServiceTree();
        esbServiceTree.setCode(esbInboundMain.getServiceid());
        esbServiceTree.setHaschildren(0);
        esbServiceTree.setLvl(2);
        esbServiceTree.setName(interfaceName);
        esbServiceTree.setStatus("1");
        esbServiceTree.setParId(1);
        try{
            esbServiceTreeService.save(esbServiceTree);
        }catch (Exception e) {
            return Response.error("注册失败，服务树目录保存出错");
        }
        // 服务适配信息注册
        if(adapterType == 1) {
            EsbInboundHttp esbInboundHttp = new EsbInboundHttp();
            esbInboundHttp.setServiceid(esbInboundMain.getServiceid());
            esbInboundHttp.setHttptype(httpType);
            try{
                esbInboundHttpService.save(esbInboundHttp);
            }catch (Exception e) {
                return Response.error("注册失败，服务适配类型保存出错");
            }
        }else if(adapterType == 2) {
            EsbInboundWebservice esbInboundWebservice = new EsbInboundWebservice();
            esbInboundWebservice.setServiceid(esbInboundMain.getServiceid());
            esbInboundWebservice.setEndpoint(url+"?wsdl");
            esbInboundWebservice.setServicename("");
            esbInboundWebservice.setPortname("");
            esbInboundWebservice.setOperationname("");
            try{
                esbInboundWebserviceService.save(esbInboundWebservice);
            }catch (Exception e) {
                return Response.error("注册失败，服务适配类型保存出错");
            }
        }else {
            return Response.error("暂不支持此类型的注册");
        }
        // 服务部署信息注册
        deploy(0, esbInboundMain.getServiceid());
        // 给服务模拟赋权
        String address = "/DCSBWeb/servlets/" + esbInboundMain.getServcode() + "@" + esbInboundMain.getServversion();
        List<String> addressList = new ArrayList<>();
        addressList.add(0, address);
        String oneIp = "127.0.0.1";
        String[] ip = {oneIp};
        openInterfaceServiceAuthority(addressList, "服务模拟/服务模拟", "服务模拟系统", ip);
        // 自动新建api并发布
        EsbServiceApi esbServiceApi = new EsbServiceApi();
        esbServiceApi.setServname(esbInboundMain.getServname());
        esbServiceApi.setServcode(esbInboundMain.getServcode());
        esbServiceApi.setServversion(esbInboundMain.getServversion());
        esbServiceApi.setDescription("");
        esbServiceApi.setName("");
        esbServiceApi.setPhone("");
        if(adapterType == 1) {
            esbServiceApi.setApiaddress("http://192.168.1.246:50021/DCSBWeb/servlets");
        }else if(adapterType == 2) {
            esbServiceApi.setApiaddress("http://192.168.1.246:50021/DCSBWeb/services");
        }
        esbServiceApi.setProvidedept("");
        esbServiceApi.setProvidedeptCode("");
        esbServiceApi.setShareType("2");
        esbServiceApi.setReqExample("");
        esbServiceApi.setRespExample("");
        esbServiceApi.setStatus("0");
        esbServiceApi.setDataUpdateCycle(1);
        esbServiceApi.setDataPlatformId(null);
        try{
            esbServiceApiService.save(esbServiceApi);
        }catch (Exception e) {
            return Response.error("注册失败，API信息新增出错");
        }
        EsbServiceApiLog esbServiceApiLog = new EsbServiceApiLog();
        esbServiceApiLog.setApiId(esbServiceApi.getId());
        esbServiceApiLog.setUsername("dir");
        esbServiceApiLog.setOperationTime(new Date());
        esbServiceApiLog.setOperationType("0");
        esbServiceApiLog.setOperationMessage("API新建");
        try{
            esbServiceApiLogService.save(esbServiceApiLog);
        }catch (Exception e) {
            return Response.error("注册失败，API信息新增日志保存出错");
        }

        return Response.success("自动注册成功");
    }

    /**
     * 原子服务编码自增,自动注册接口
     * @return
     */
    private String atomCodeAutoincrement() {
        List<EsbAtomservice> esbAtomserviceResult = esbAtomServiceService.selectAtomServiceByCodeLikeRight("dir");
        if(esbAtomserviceResult.size() == 0 ) {
            return "dir10000";
        }else {
            String atomCode = esbAtomserviceResult.get(0).getAtomserviceCode();
            Integer atomCodeInteger = Integer.valueOf(atomCode.substring(3));
            atomCodeInteger++;
            atomCode = "dir" + atomCodeInteger.toString();
            return atomCode;
        }
    }

    /**
     * 服务编码自增,自动注册接口
     * @return
     */
    private String serviceCodeAutoincrement() {
        QueryWrapper<EsbInboundMain> esbInboundMainQueryWrapper = new QueryWrapper<>();
        esbInboundMainQueryWrapper.likeRight("servcode", "33.1111.dir.dir");
        esbInboundMainQueryWrapper.orderByDesc("servcode");
        List<EsbInboundMain> esbInboundMainResult = esbInboundMainService.list(esbInboundMainQueryWrapper);
        if(esbInboundMainResult.size() == 0 ) {
            return "33.1111.dir.dir10000.SynReq";
        }else {
            String serviceCode = esbInboundMainResult.get(0).getServcode();
            Integer serviceCodeInteger = Integer.valueOf(serviceCode.substring(0, serviceCode.length()-7).substring(15));
            serviceCodeInteger++;
            serviceCode = "33.1111.dir.dir" + serviceCodeInteger.toString() + ".SynReq";
            return serviceCode;
        }
    }

    /**
     * 新增部署信息
     * @param deploytype 部署类别：0:部署的是标准服务,1:部署的是原子服务
     */
    private void deploy(Integer deploytype, Integer id) {
        String applicationType = "app";
        if(deploytype == 1) {
            applicationType = "subapp";
        }else if(deploytype == 0) {
            applicationType = "app";
        }else if(isEmpty(deploytype)) {
            applicationType = "subapp";
        }
        QueryWrapper<EsbApp> wrapper = new QueryWrapper<>();
        wrapper.likeRight("appname",applicationType);
        wrapper.orderByAsc("appname");
        List<EsbApp> esbAppResult = esbAppService.list(wrapper);
        for(int i=0; i<esbAppResult.size(); i++) {
            EsbServiceAtomDeploy esbServiceAtomDeploy = new EsbServiceAtomDeploy();
            esbServiceAtomDeploy.setDomainname(esbAppResult.get(i).getDomainname());
            esbServiceAtomDeploy.setInstancename(esbAppResult.get(i).getAppname());
            esbServiceAtomDeploy.setServiceid(id);
            if("1".equals(esbAppResult.get(i).getStatus())){
                esbServiceAtomDeploy.setStatus("1");
            }else {
                esbServiceAtomDeploy.setStatus("0");
            }
            esbServiceAtomDeploy.setLastupdateTime(new Date());
            esbServiceAtomDeploy.setDeploytype(deploytype);
            esbServiceAtomDeployService.save(esbServiceAtomDeploy);
        }
    }

}
